package com.artisan.springuitls.demos;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;

import java.util.List;

/**
 * MimeTypeUtils 工具类演示
 * 功能：MIME 类型解析器
 * 优势：安全解析 MIME 类型字符串，避免 new MediaType() 的空指针风险
 */
@Component
public class MimeTypeUtilsDemo {

    /**
     * 场景：根据文件后缀设置响应头
     */
    public MediaType resolveMimeType(String fileType) {
        System.out.println("\n========== MimeTypeUtils Demo ==========");
        
        // ✅ 安全解析：失败返回 null
        MimeType mimeType = MimeTypeUtils.parseMimeType(fileType);
        
        // ✅ 默认回退
        MediaType mediaType = mimeType != null ? 
            new MediaType(mimeType.getType(), mimeType.getSubtype()) : 
            MediaType.APPLICATION_OCTET_STREAM;
        
        System.out.println("✓ 文件类型 '" + fileType + "' 解析为: " + mediaType);
        return mediaType;
    }

    /**
     * 演示常用 MIME 类型常量
     */
    public void demonstrateCommonMimeTypes() {
        System.out.println("\n--- 常用 MIME 类型常量 ---");
        
        System.out.println("✓ ALL: " + MimeTypeUtils.ALL); // */*
        System.out.println("✓ APPLICATION_JSON: " + MimeTypeUtils.APPLICATION_JSON);
        System.out.println("✓ APPLICATION_XML: " + MimeTypeUtils.APPLICATION_XML);
        System.out.println("✓ TEXT_HTML: " + MimeTypeUtils.TEXT_HTML);
        System.out.println("✓ TEXT_PLAIN: " + MimeTypeUtils.TEXT_PLAIN);
        System.out.println("✓ TEXT_XML: " + MimeTypeUtils.TEXT_XML);
        System.out.println("✓ IMAGE_GIF: " + MimeTypeUtils.IMAGE_GIF);
        System.out.println("✓ IMAGE_JPEG: " + MimeTypeUtils.IMAGE_JPEG);
        System.out.println("✓ IMAGE_PNG: " + MimeTypeUtils.IMAGE_PNG);
        System.out.println("✓ MULTIPART_FORM_DATA: multipart/form-data");
        System.out.println("✓ APPLICATION_OCTET_STREAM: " + MimeTypeUtils.APPLICATION_OCTET_STREAM);
        
        System.out.println();
    }

    /**
     * 演示 MIME 类型解析
     */
    public void demonstrateMimeTypeParsing() {
        System.out.println("\n--- MIME 类型解析 ---");
        
        // 1. 解析简单类型
        MimeType json = MimeTypeUtils.parseMimeType("application/json");
        System.out.println("✓ JSON 类型: " + json);
        System.out.println("  - 主类型: " + json.getType());
        System.out.println("  - 子类型: " + json.getSubtype());
        
        // 2. 解析带参数的类型
        MimeType textWithCharset = MimeTypeUtils.parseMimeType(
            "text/html; charset=UTF-8");
        System.out.println("✓ HTML 类型: " + textWithCharset);
        System.out.println("  - 字符集: " + textWithCharset.getParameter("charset"));
        
        // 3. 解析带多个参数
        MimeType multipart = MimeTypeUtils.parseMimeType(
            "multipart/form-data; boundary=----WebKitFormBoundary");
        System.out.println("✓ Multipart 类型: " + multipart);
        System.out.println("  - boundary: " + multipart.getParameter("boundary"));
        
        // 4. 解析失败处理
        try {
            MimeType invalid = MimeTypeUtils.parseMimeType("invalid-mime-type");
            System.out.println("✓ 无效类型: " + invalid);
        } catch (Exception e) {
            System.out.println("✓ 解析失败（预期）: " + e.getMessage());
        }
        
        System.out.println();
    }

    /**
     * 演示 MIME 类型比较
     */
    public void demonstrateMimeTypeComparison() {
        System.out.println("\n--- MIME 类型比较 ---");
        
        MimeType json1 = MimeTypeUtils.APPLICATION_JSON;
        MimeType json2 = MimeTypeUtils.parseMimeType("application/json");
        MimeType jsonUtf8 = MimeTypeUtils.parseMimeType("application/json;charset=UTF-8");
        
        // 相等比较
        System.out.println("✓ json1 equals json2: " + json1.equals(json2)); // true
        System.out.println("✓ json1 equals jsonUtf8: " + json1.equals(jsonUtf8)); // false
        
        // 兼容性比较（忽略参数）
        System.out.println("✓ json1 isCompatibleWith jsonUtf8: " + 
            json1.isCompatibleWith(jsonUtf8)); // true
        
        // 通配符匹配
        MimeType all = MimeTypeUtils.ALL;
        System.out.println("✓ ALL includes json: " + all.includes(json1)); // true
        
        // 具体类型包含
        MimeType textAll = MimeTypeUtils.parseMimeType("text/*");
        MimeType textHtml = MimeTypeUtils.TEXT_HTML;
        MimeType appJson = MimeTypeUtils.APPLICATION_JSON;
        System.out.println("✓ text/* includes text/html: " + textAll.includes(textHtml)); // true
        System.out.println("✓ text/* includes application/json: " + textAll.includes(appJson)); // false
        
        System.out.println();
    }

    /**
     * 演示 MIME 类型列表解析
     */
    public void demonstrateMimeTypeListParsing() {
        System.out.println("\n--- MIME 类型列表解析 ---");
        
        // 解析 Accept 请求头
        String acceptHeader = "application/json, text/html, application/xml;q=0.9, */*;q=0.8";
        List<MimeType> mimeTypes = MimeTypeUtils.parseMimeTypes(acceptHeader);
        
        System.out.println("✓ Accept 头解析结果:");
        for (int i = 0; i < mimeTypes.size(); i++) {
            MimeType mt = mimeTypes.get(i);
            System.out.println("  " + (i+1) + ". " + mt);
        }
        
        System.out.println();
    }

    /**
     * 演示 MIME 类型排序
     */
    public void demonstrateMimeTypeSorting() {
        System.out.println("\n--- MIME 类型排序 ---");
        
        // 创建多个 MIME 类型
        String acceptHeader = "text/html, application/xml;q=0.9, application/json, */*;q=0.8";
        List<MimeType> mimeTypes = MimeTypeUtils.parseMimeTypes(acceptHeader);
        
        System.out.println("✓ 解析前:");
        mimeTypes.forEach(mt -> System.out.println("  - " + mt));
        
        // 按质量因子排序
        MimeTypeUtils.sortBySpecificity(mimeTypes);
        
        System.out.println("✓ 按特定性排序后:");
        mimeTypes.forEach(mt -> System.out.println("  - " + mt));
        
        System.out.println();
    }

    /**
     * 实际应用场景：内容协商
     */
    public void demonstrateContentNegotiation() {
        System.out.println("\n--- 内容协商场景 ---");
        
        // 客户端接受的类型
        String acceptHeader = "application/xml, application/json;q=0.9, text/html;q=0.8";
        List<MimeType> clientAccepts = MimeTypeUtils.parseMimeTypes(acceptHeader);
        
        // 服务器支持的类型
        List<MimeType> serverProduces = List.of(
            MimeTypeUtils.APPLICATION_JSON,
            MimeTypeUtils.TEXT_HTML
        );
        
        System.out.println("✓ 客户端接受: " + clientAccepts);
        System.out.println("✓ 服务器支持: " + serverProduces);
        
        // 找到最佳匹配
        MimeType bestMatch = findBestMatch(clientAccepts, serverProduces);
        System.out.println("✓ 最佳匹配: " + bestMatch);
        
        System.out.println();
    }

    /**
     * 实际应用场景：文件下载响应头设置
     */
    public void demonstrateFileDownload() {
        System.out.println("\n--- 文件下载场景 ---");
        
        // 根据文件扩展名确定 MIME 类型
        String[][] fileExtensions = {
            {"document.pdf", "application/pdf"},
            {"image.jpg", "image/jpeg"},
            {"data.json", "application/json"},
            {"page.html", "text/html"},
            {"archive.zip", "application/zip"},
            {"video.mp4", "video/mp4"}
        };
        
        System.out.println("✓ 文件类型映射:");
        for (String[] file : fileExtensions) {
            String filename = file[0];
            String mimeTypeStr = file[1];
            MimeType mimeType = MimeTypeUtils.parseMimeType(mimeTypeStr);
            
            System.out.println("  - " + filename + " -> " + mimeType);
            System.out.println("    Content-Type: " + mimeType);
            System.out.println("    Content-Disposition: attachment; filename=\"" + filename + "\"");
        }
        
        System.out.println("==========================================\n");
    }

    /**
     * 辅助方法：找到最佳匹配的 MIME 类型
     */
    private MimeType findBestMatch(List<MimeType> clientAccepts, List<MimeType> serverProduces) {
        for (MimeType clientType : clientAccepts) {
            for (MimeType serverType : serverProduces) {
                if (clientType.isCompatibleWith(serverType)) {
                    return serverType;
                }
            }
        }
        return MimeTypeUtils.APPLICATION_OCTET_STREAM;
    }

    /**
     * 最佳实践
     */
    public void printBestPractices() {
        System.out.println("\n========== 最佳实践 ==========");
        System.out.println("✓ 1. 使用常量而非字符串字面量");
        System.out.println("✓ 2. parseMimeType() 比 new MimeType() 更安全");
        System.out.println("✓ 3. 使用 isCompatibleWith() 做兼容性检查");
        System.out.println("✓ 4. 内容协商时排序客户端接受类型");
        System.out.println("✓ 5. 文件下载务必设置正确的 Content-Type");
        System.out.println("✓ 6. 与 Spring Web 的 ContentNegotiationManager 集成");
        System.out.println("==========================================\n");
    }
}

